/*
 * Ammo.cpp
 *
 *  Created on: 31/10/2011
 */

#include "Ammo.h"
#include "../../common/lib/SDL_rotozoom.h"


Ammo::Ammo(ammoTypeEnum ammoType,int posX, int posY, Widget *parent, int angle, int duration,std::string ammoImage,int ammoVelocity,int damage,std::string ammoSoundEffect) :
	WidgetMovimiento(AMMO,posX, posY,angle,ammoImage, parent,damage), WidgetSonido(ammoSoundEffect) {

	this->ammoType =  ammoType;

	this->velocity = ammoVelocity;
	this->maxDuration = duration;
	this->timeAlive = 0;

	nextX += getOffsetX() * 1.5;
	nextY -= getOffsetY() * 1.5;

	this->playSound();

}


int Ammo::getOffsetY() {
	float angleInRadians = angle * (M_PI / 180.0);
	return this->surface->clip_rect.w/2 * sin(angleInRadians);
}


int Ammo::getOffsetX() {
	float angleInRadians = angle * (M_PI / 180.0);
	return this->surface->clip_rect.w/2 * cos(angleInRadians);
}


void Ammo::resolve() {

	if (drawable) {
		//Timer to get seconds between frames
		if (!timer.is_started()) {
			timer.start();
		}

		float secsPerFrame = timer.get_ticks() / 1000.0;
		timeAlive += secsPerFrame;
		if (timeAlive <= maxDuration) {

			parcel->posX = nextX;
			parcel->posY = nextY;

			int posX0 = parcel->posX;
			int posY0 = parcel->posY;

			float angleInRadians = angle * (M_PI / 180);

			float velX = velocity * cos(angleInRadians);
			float velY = (-1.0) * velocity * sin(angleInRadians);

			float deltaX = fabs(velX * secsPerFrame);
			deltaX = floor(deltaX * 100) / 100;
			deltaX = floor(deltaX + 0.5);
			float deltaY = fabs(velY * secsPerFrame);
			deltaY = floor(deltaY * 100) / 100;
			deltaY = floor(deltaY + 0.5);

			if(velX >= 0)
				nextX = posX0 + deltaX;
			else if(velX < 0)
				nextX = posX0 - deltaX;

			if (velY >= 0)
				nextY = posY0 + deltaY;
			else if (velY < 0)
				nextY = posY0 - deltaY;

			timer.start();

		} else {
			this->drawable = false;
			timer.stop();
		}
	}

	WidgetMovimiento::resolve();

}

ammoTypeEnum Ammo::getAmmoType() const
{
    return ammoType;
}

Ammo::~Ammo() {
}

void Ammo::handleColision(WidgetMovimiento* with){

	if( with->getType() == SHIP || with->getType() == ASTEROID || with->getType() == SHIP_BASE){
		this->drawable = false;
	}

}
